package alf.mapping.data;
import alf.common.data.AbstractDataService;
import alf.common.data.DataException;
import alf.mapping.dto.maps.Item;
import alf.mapping.dto.maps.MapModel;
import alf.mapping.dto.maps.Room;
import android.graphics.Rect;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParserException;

public class SimpleLoader extends AbstractDataService {

	private static final long TAM = 500;

	private String[] objs = {
		"armario","impresora","mesa-ordenador",
		"mesa","silla","mesasilla","mesachica",
		"monitor","teclado"
	};
	
	public MapModel getModel(String name) throws DataException {
		if (name.equalsIgnoreCase("random")){
			return getRandomModel();
		} else if (name.equalsIgnoreCase("ref")){
			return getRefModel();
		} else if (name.equalsIgnoreCase("empty")){
			return empty();
		} else {
			return load(name);
		}
	}
	
	public MapModel load(String path) throws DataException {
		File f = new File(path);
		MapParser p = new MapParser();
		MapModel m = null;
		try {
			FileInputStream input = new FileInputStream(f);
			 m = p.parse(input);
		} catch (FileNotFoundException e) {
			encapsula("file not found.",e);
		} catch (XmlPullParserException e2) {
			encapsula("xml parsing error.",e2);
		} catch (IOException e3){
			encapsula("file reading error.",e3);
		}
		return m;
	}
	
	public MapModel empty() {
		MapModel m = new MapModel();
		Room r = new Room();
		m.addRoom(r);
		return m;
	}
	
	public MapModel getRefModel(){
		MapModel m = new MapModel();
		Room r = new Room();
		r.setName("diagram 1");
		r.setMod("office");
		Item item = createItem(1,r);
		item.setRect(new Rect(0,0,0,0));
		m.addRoom(r);
		return m;
	}

	private Item createItem(int i,Room r) {
		Item e = new Item();
		int idx = (int) (Math.random() * objs.length);
		e.setName(objs[idx] + (i + 1));
		e.setType(objs[idx]);
		e.getRect().set(aleat(), aleat(), 0, 0);
		r.addEntity(e);
		return e;
	}

	public MapModel getRandomModel() {
		MapModel m = new MapModel();
		int mRooms, mObj;

		Room r;
		mRooms = 4;
		for (int k=0;k < mRooms;k++) {
			r = new Room();
			r.setMod("office");
			mObj = (int) (Math.random()*10)+1;
			for (int i=0;i<mObj;i++) {
				Item e = new Item();
				int idx = (int) (Math.random()*objs.length);
				e.setName(objs[idx]+(i+1));
				e.setType(objs[idx]);
				e.getRect().set(aleat(),aleat(),0,0);
			//	e.setPosition(new Vector2d((float)Math.random(), (float)Math.random()));
			//	e.getPosition().scale(TAM);
				r.addEntity(e);
			}
			m.addRoom(r);
		}
		return m;
	}

	private int aleat() {
		return (int)(TAM*Math.random());
	}
}
